<?php

namespace app\services;

use app\payment\PayFactory;
use plugin\admin\app\model\CoinTask;
use plugin\admin\app\model\UserPropertyLog;
use support\Cache;
use support\Db;

class CoinService
{
    public static function exchangeToSD($sd)
    {
        $needSB = ExchangeRateService::getTodayExchangeRate() * 1000 * $sd;

        PropertyService::reduce(get_user_id(), PayFactory::SB, $needSB, UserPropertyLog::EXCHANGE_TO_SD);
        PropertyService::add(get_user_id(), PayFactory::SD, $sd, UserPropertyLog::FROM_SB);
    }


    public static function list()
    {
        $tasks = CoinTask::where('user_id', get_user_id())->whereNotNull('final_coin')->orderByDesc('id')->offset(0)->limit(7)->get()->toArray();

        $data = [];
        for ($i=6; $i>=1; $i--) {
            $date = date('Y-m-d', strtotime('-' . $i . ' days'));
            $tempData = [
                'date' => $date,
                'coin' => 0,
            ];

            foreach ($tasks as $task) {
                if ($task['date'] == $date) {
                    $tempData = [
                        'date' => $date,
                        'coin' => $task['final_coin']
                    ];
                    break;
                }
            }

            $data[] = $tempData;

        }

        return $data;
    }

    public static function addTask()
    {
        $startTime = time();
        $endTime = strtotime('+1 day');

        if (self::getBootTask()['exists']) {
            throw new \Exception('实时币收益已启动');
        }

        $baseSpeed = ExchangeRateService::getBaseRate();
        $teamSpeed = ExchangeRateService::getTeamRate();

        return CoinTask::insertGetId([
            'user_id' => get_user_id(),
            'start_time' => $startTime,
            'end_time' => $endTime,
            'speed' => bcadd($baseSpeed, $teamSpeed, 2),
            'created_time' => date('Y-m-d H:i:s')
        ]);

    }

    public static function getBootTask()
    {
        $currentTimestamp = time();
        $task = CoinTask::where('start_time', '<=', $currentTimestamp)->where('end_time', '>=', $currentTimestamp)->where('user_id', get_user_id())->first();

        if ($task) {
            return [
                'exists' => true,
                'rest_time' => $task['end_time'] - time(),
                'speed' => $task['speed'],
                'coin' => bcmul($task['speed']/3600, (time() - $task['start_time']), 2)
            ];
        }

        return [
            'exists' => false
        ];
    }

    public static function autoFinishTask()
    {
        $tasks = CoinTask::where('end_time', '<=', time())->whereNull('final_coin')->get()->toArray();

        foreach ($tasks as $task) {
            Db::beginTransaction();

            try {
                $coin = bcmul(($task['end_time'] - $task['start_time']) / 3600, $task['speed'], 2);
                CoinTask::where('id', $task['id'])->update([
                    'finia_coin' =>  $coin
                ]);

                PropertyService::add($task['user_id'], PayFactory::SB, $coin, UserPropertyLog::COIN_GET, '');

                Db::commit();
            } catch (\Exception $e) {
                Db::rollBack();
            }

        }
    }

}